/**
 * 
 */
package org.compiere.process;

import java.io.File;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.logging.Level;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.adempiere.exceptions.AdempiereException;
import org.compiere.apps.ADialog;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MBPMStandartHours;
import org.compiere.model.MBPMStandartJob;
import org.compiere.model.MBPMVersionBudget;
import org.compiere.model.MYear;
import org.compiere.model.MbpmstandartCharge;
import org.compiere.model.X_BPM_VersionBudget;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import extend.org.compiere.hrm.ExcelCell;
import extend.org.compiere.utils.Util;

/**
 * @author V.Sokolov
 *
 */
public class BPMStandartHoursReport extends SvrProcess {
	
	/* Current context */
	private Properties m_ctx;
	/* */
	private ProcessInfo pi;
	/* */
	private int BPM_VersionBudget_ID = 0;
	private int BPM_Project_ID = 0;
	private int Profitability = 0;
	private int VAT = 0;
	private int StandartHours = 0;
	/* */
	X_BPM_VersionBudget version = null;
	/* */
	private String path = Util.localFilePath;
	
	/* 
	 */
	@Override
	protected void prepare() {
		
		log.info(" Report AMP ");
		m_ctx = Env.getCtx();
		pi = getProcessInfo();
		
		ProcessInfoParameter[] para = getParameter();
		for (int i = 0; i < para.length; i++)	{
			String name = para[i].getParameterName();
			if (name == null); 
				//
			else if (name.compareTo("BPM_VersionBudget_ID") == 0 && para[i].getParameter() != null)
				BPM_VersionBudget_ID = new BigDecimal(Integer.parseInt(para[i].getParameter().toString())).intValue();
			else if (name.compareTo("BPM_Project_ID") == 0 && para[i].getParameter() != null)
				BPM_Project_ID = new BigDecimal(Integer.parseInt(para[i].getParameter().toString())).intValue();
			else if (name.compareTo("Profitability") == 0 && para[i].getParameter() != null)
				Profitability = new BigDecimal(Integer.parseInt(para[i].getParameter().toString())).intValue();
			else if (name.compareTo("VAT") == 0 && para[i].getParameter() != null)
				VAT = new BigDecimal(Integer.parseInt(para[i].getParameter().toString())).intValue();
			else if (name.compareTo("StandartHours") == 0 && para[i].getParameter() != null)
				StandartHours = new BigDecimal(Integer.parseInt(para[i].getParameter().toString())).intValue();
			else
			{
				log.log(Level.INFO, "Unknown Parameter: " + name);
			}
		}
		
		version = new MBPMVersionBudget(m_ctx, BPM_VersionBudget_ID, get_TrxName());

	}

	/* 
	 */
	@Override
	protected String doIt() throws Exception {

		//
		MAttachmentEntry entry = Util.getAttachment(pi, m_ctx, null);
		if(entry == null)
			throw new AdempiereException(Msg.translate(m_ctx, "NotFoundTemplate"));
		
		String templateName = "StandartHours";
		
		// We define a path to generate
		String fileExtension = entry.getName().substring(entry.getName().lastIndexOf("."),entry.getName().length());
		StringBuffer fullPath = new StringBuffer(path);		
		fullPath.append(templateName+"T").append(fileExtension);
		
		// Types of cells for
		Label label;
		Number number;
				
		// 
		File templateCopy = new File(fullPath.toString());
		File temporaryFile = entry.getFile(Util.localFilePath+templateName);
		Workbook tableBook = null;
		WritableWorkbook copy = null;
		WritableSheet sheet = null;
		try {
			tableBook = Workbook.getWorkbook(temporaryFile);
			copy = Workbook.createWorkbook(templateCopy, tableBook);
			sheet = copy.getSheet(0);
		} catch (Exception e) {
			ADialog.error(999, null, "Error tableBook. " + e.getMessage());
		    return "Error tableBook.";
		}

		ExcelCell cellStart1 =  Util.getCellStart(tableBook,">>");
		
		// Standart style cell
	    WritableCellFormat borderStyle = new WritableCellFormat();
	    borderStyle.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
	    borderStyle.setAlignment(Alignment.CENTRE);
	    borderStyle.setVerticalAlignment(VerticalAlignment.CENTRE);
	    borderStyle.setWrap(true);
	    // Job style cell
	    WritableCellFormat jobStyle = new WritableCellFormat();
	    jobStyle.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
	    jobStyle.setAlignment(Alignment.LEFT);
	    jobStyle.setVerticalAlignment(VerticalAlignment.CENTRE);
	    jobStyle.setWrap(true);
	    // Vacation style cell
	    WritableFont fontTot = new WritableFont (WritableFont.TIMES, 12, WritableFont.BOLD);
	    WritableCellFormat cellTotal = new WritableCellFormat(fontTot);
	    cellTotal.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
	    cellTotal.setAlignment(Alignment.CENTRE);
	    cellTotal.setVerticalAlignment(VerticalAlignment.CENTRE);
	    // Title style cell
	    WritableFont fontTitle = new WritableFont (WritableFont.TIMES, 12, WritableFont.BOLD);
	    WritableCellFormat titleStyle = new WritableCellFormat(fontTitle);
	    titleStyle.setAlignment(Alignment.CENTRE);
	    titleStyle.setVerticalAlignment(VerticalAlignment.CENTRE);
	    titleStyle.setWrap(true);
	    // Avarage style cell
	    WritableFont fontAvarage = new WritableFont (WritableFont.TIMES, 11, WritableFont.NO_BOLD);
	    WritableCellFormat avarageCell = new WritableCellFormat(fontAvarage);
	    avarageCell.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
	    avarageCell.setAlignment(Alignment.RIGHT);
	    avarageCell.setVerticalAlignment(VerticalAlignment.CENTRE);
	    // Total style cell
	    WritableFont fontTotal = new WritableFont (WritableFont.TIMES, 11, WritableFont.BOLD);
	    WritableCellFormat totalStyle = new WritableCellFormat(fontTotal);
	    totalStyle.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
	    totalStyle.setAlignment(Alignment.RIGHT);
	    totalStyle.setVerticalAlignment(VerticalAlignment.CENTRE);
	    
	    MYear y = new MYear(m_ctx, version.getC_Year_ID(), get_TrxName());
	    Object[] param = new Object[]{y.getFiscalYear()};
	 	
	 	label = new Label(1, 1, MessageFormat.format("Расчет стоимости услуг (работ) на {0} год, оказываемых "+Util.getOrgInfo().getDescription(), param), titleStyle);
		sheet.addCell(label);
		
	    int col1 = cellStart1.getC();
	    int row1 = cellStart1.getR();
	    
	    MBPMStandartHours stHours = MBPMStandartHours.getMBPMStandartHours(BPM_Project_ID);
	    if(stHours == null)
	    	throw new AdempiereException("Данные не найдены");
		MBPMStandartJob[] jobLines = MBPMStandartHours.getLinesJob(m_ctx, BPM_Project_ID, get_TrxName());
		double costs = MBPMStandartHours.getCosts(stHours.getBPM_StandartHours_ID());
		
		int i = row1;
		double fot = 0;
		double fotC = 0;
		double fotTotal = 0;
		double percentProfitability = 0;
		double percentVAT = 0;
		double total = 0;
		for(MBPMStandartJob job: jobLines){
			
	    	fot = job.getPayrollAmount().add(job.gethrm_CNalog()).add(new BigDecimal(costs)).doubleValue();
	    	percentProfitability = ((fot/100)*Profitability);
	    	fotC = fot + percentProfitability;
	    	percentVAT = ((fotC)/100)*VAT;
	    	fotTotal = fotC + percentVAT;

			// #
			label = new Label(col1, i, job.getName(), jobStyle); 
	    	sheet.addCell(label);
	    	//
	    	number = new Number(col1+1, i, fot, avarageCell);
	    	sheet.addCell(number);
	    	//
	    	label = new Label(col1+2, i, Profitability+"%" , borderStyle); 
	    	sheet.addCell(label);
	    	//
	    	label = new Label(col1+3, i, VAT+"%" , borderStyle); 
	    	sheet.addCell(label);
	    	//
	    	label = new Label(col1+4, i, StandartHours+" часа" , borderStyle); 
	    	sheet.addCell(label);
	    	//
	    	if(StandartHours != 0)
	    		total = (fotTotal/StandartHours)*1000;
	    	else
	    		total = 0;
	    	number = new Number(col1+5, i, Math.round(total), totalStyle);
	    	sheet.addCell(number);
	    	
	    	i++;
	    	sheet.insertRow(i+1);
		}
		
		int j = i+5;
		for(MBPMStandartJob job1: jobLines){

			// #
			label = new Label(col1, j, job1.getName(), jobStyle); 
	    	sheet.addCell(label);
	    	//
	    	number = new Number(col1+1, j, job1.gethrm_amountsalary().doubleValue(), avarageCell);
	    	sheet.addCell(number);
	    	//
	    	number = new Number(col1+2, j, job1.getPayrollAmount().doubleValue(), avarageCell);
	    	sheet.addCell(number);
	    	//
	    	number = new Number(col1+3, j, job1.gethrm_CNalog().doubleValue(), avarageCell);
	    	sheet.addCell(number);
	    	
	    	j++;
	    	sheet.insertRow(j+1);
		}
		
		MbpmstandartCharge[] chargeLines = MbpmstandartCharge.getLines(m_ctx, stHours.getBPM_StandartHours_ID(), get_TrxName());
		
		int n = j+5;
		double totalCharge = 0;
		double totalAmount = 0;
		for(MbpmstandartCharge ch: chargeLines){

			// #
			label = new Label(col1, n, ch.getChargeName(), jobStyle); 
	    	sheet.addCell(label);
	    	//
	    	number = new Number(col1+1, n, ch.getAmount().doubleValue(), avarageCell);
	    	sheet.addCell(number);
	    	//
	    	number = new Number(col1+2, n, ch.getCountEmployee(), borderStyle);
	    	sheet.addCell(number);
	    	//
	    	number = new Number(col1+3, n, ch.getamountemployee().doubleValue(), avarageCell);
	    	sheet.addCell(number);
			
	    	totalCharge = totalCharge + ch.getamountemployee().doubleValue();
	    	totalAmount = totalAmount + ch.getAmount().doubleValue();
	    	
			n++;
			sheet.insertRow(n+1);
		}
		
		label = new Label(col1, n, "ИТОГО", cellTotal); 
    	sheet.addCell(label);
    	//
    	number = new Number(col1+1, n, totalAmount, avarageCell);
    	sheet.addCell(number);
    	//
    	number = new Number(col1+2, n, chargeLines[0].getCountEmployee(), borderStyle); 
    	sheet.addCell(number);
    	//
    	number = new Number(col1+3, n, totalCharge, totalStyle);
    	sheet.addCell(number);
		
		copy.write();
	    copy.close();
	    tableBook.close();
	    temporaryFile.delete();
	    
	    // Open the file with the application associated
	 	String fileName = fullPath.toString();
	 	Util.launchFile(new File(fileName));
	 	
		return Msg.translate(m_ctx, "Success");
	}
	

}
